﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;

namespace Dominio.Logica
{
    public class Log
    {
        public static void Grabar(string texto)
        {
           
            string[] rutaLog = System.Configuration.ConfigurationManager.AppSettings.GetValues("RutaLog");
            string archivo = "Log_" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + ".txt";

            string[] encriptaLog = (System.Configuration.ConfigurationManager.AppSettings.GetValues("EncriptaLog"));

            if (!File.Exists(rutaLog[0] + archivo)) 
            {
                StreamWriter sw = new StreamWriter(rutaLog[0] + archivo);
                if (encriptaLog[0].Equals("SI")){
                    sw.WriteLine(Encriptador.EncryptStringAES(DateTime.Now + " : " + texto,""));
                }
                else{
                    sw.WriteLine(string.Format("{0}: {1}", DateTime.Now, texto));
                }
                sw.Close();
            }

            using (StreamWriter sw = File.AppendText(rutaLog[0] + archivo))
            {
                if (encriptaLog[0].Equals("SI"))
                {
                    sw.WriteLine(Encriptador.EncryptStringAES(DateTime.Now + " : " + texto, ""));
                }
                else
                {
                    sw.WriteLine(string.Format("{0}: {1}", DateTime.Now, texto));
                }
                sw.Close();
            }	
        }

        public static string RecuperarLog(string ruta) 
        {
            string salida = null;
            // Open and read the file.
            StreamReader r = File.OpenText(ruta);
            string[] encriptaLog = (System.Configuration.ConfigurationManager.AppSettings.GetValues("EncriptaLog"));

            if (encriptaLog[0].Equals("SI"))
            {
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    salida += Encriptador.DecryptStringAES(line,"");
                    salida += Environment.NewLine;
                }

            }
            else
            {
                
                string line;
                while ((line = r.ReadLine()) != null)
                {
                    salida += line;
                    salida += Environment.NewLine;
                }
            }
            r.Close();
            return salida;
            
        }

    }
}
